package table_user

import (
	"time"

	"gitee.com/klein-x/biz/model/mysql/table"
	"gitee.com/klein-x/biz/module/db/mysql"
	"gitee.com/klein-x/biz/xutils"
)

// Asset 存储用户资产记录
type UserAsset struct {
	AssetID   string `gorm:"primaryKey;type:char(36);unique;not null;comment:'资产ID'"`
	UserUUID  string `gorm:"type:char(36);not null;comment:'用户UUID'"`
	ChapterID string `gorm:"type:char(36);not null;comment:'章节ID'"`
	StartTime uint64 `gorm:"type:bigint unsigned;not null;comment:'获取日期'"`
	EndTime   uint64 `gorm:"type:bigint unsigned;not null;comment:'到期日期'"`
	Status    string `gorm:"type:char(1);not null;default:'0';comment:'资产状态, 正常 0'"`
	Note      string `gorm:"type:text;comment:'备注信息'"`
}

// TableName 指定自定义表名
func (a *UserAsset) TableName() string {
	return "user_assets"
}

func AssetsDefine(uuid, chapterId string) *UserAsset {
	var asset UserAsset
	id, err := xutils.RandomUUID()
	if err != nil {
		return nil
	}
	asset.AssetID = id
	asset.UserUUID = uuid
	asset.ChapterID = chapterId
	asset.StartTime = 0
	asset.EndTime = 0
	asset.Status = "0"
	asset.Note = ""
	return &asset
}

// GetNormalUserAssets 查询指定用户的正常资产
func AssetsGetByUser(userUUID string) (*[]UserAsset, error) {
	db := mysql.GetGlobalDB() // 获取全局数据库连接

	var userAssets []UserAsset

	// 转换为秒级时间戳
	timestamp := time.Now().Unix()

	return table.SelectCheck(&userAssets, db.Where("user_uuid = ? AND status = ? AND end_time > ?", userUUID, "0", timestamp).Find(&userAssets))
}

func AssetsGetByUserAndChapterID(userUUID string, chapterId string) (*UserAsset, error) {
	db := mysql.GetGlobalDB() // 获取全局数据库连接

	var userAssets UserAsset
	return table.SelectCheck(&userAssets, db.Where("user_uuid = ? AND status = ? AND chapter_id = ?", userUUID, "0", chapterId).First(&userAssets))
}

func AssetsInsert(assets *UserAsset) error {
	db := mysql.GetGlobalDB()
	return table.InsertCheck(db.Create(assets))
}

func AssetsUpadte(assets *UserAsset) error {
	db := mysql.GetGlobalDB()
	return table.UpdateCheck(db.Save(assets))
}
